/**
 * Created by liold on 2015/2/15.
 */

var courseId = 0;
var teachingPlanList = null;
// init
$(function () {
    $("#btn-add").click(addMergedClass);
    $("#btn-remove").click(removeMergedClass);

    $("#div-course a").each(function () {
        $(this).click(function () {
            $("#div-course a").removeClass("selected");
            $(this).addClass("selected");
            courseId = $(this).attr("courseId");
            getUnMergedClasses(courseId);
        });
    });

    $("#div-mergedclass a").each(function () {
        $(this).click(function () {
            $("#div-mergedclass a").removeClass("selected");
            $(this).addClass("selected");
        });
    });
});

/**
 * 获取未合并的班级
 */
function getUnMergedClasses() {
    if (courseId <= 0) {  // no selected course
        return;
    }
    var $div_class = $("#div-class");
    $div_class.empty();
    jQuery.ajax({
        url: "/m/rule/getUnMergedClasses?taskId=" + taskId + "&courseId=" + courseId,
        cache: false,
        success: function (ret) {
            if (ret != "") {
                var classCourseTeachers = eval(ret);
                if(classCourseTeachers == null){
                    return;
                }
                for (var i = 0; i < classCourseTeachers.length; i++) {

                    var cct = classCourseTeachers[i];

                    var $a = $(document.createElement("a"));
                    //$a.attr("href", "javascript:void(0)");
                    var txt = cct.gradeName + cct.className + "(" + cct.teacherName + ")";
                    $a.text(txt);
                    //class="list-group-item" classId="" teacherId=""
                    $a.addClass("list-group-item");
                    $a.attr("classId", cct.classId);
                    $a.attr("teacherId", cct.teacherId);
                    $a.attr("groupId", cct.groupId)
                    $a.click(function () {
                        //if ($(this).hasClass("selected")) {
                        //    alert("d")
                        //    $(this).removeClass("selected");
                        //    $(this).addClass("unselected");
                        //}
                        //else {
                        //    alert("ds")
                        //    $(this).removeClass("unselected");
                        //    $(this).addClass("selected");
                        //}
                        $(this).toggleClass("selected");
                    });
                    $div_class.append($a[0]);
                }
            }
        }
    });
}

/**
 * 是否检查预排
 * @param classId
 * @param teachId
 * @returns {boolean}
 */
function checkPreSchedule(classId, teachId){
    for(var i = 0; i < teachingPlanList.length; i++){
        var teachingPlan = teachingPlanList[i];
        if(teachingPlan.preSchedules != "" && teachingPlan.preSchedules != null
            && teachingPlan.courseId == courseId
            && teachingPlan.teacherId == teachId && teachingPlan.classId == classId){
            //console.log(teachingPlan);
            return false;
        }
    }
    return true;
}

function addMergedClass() {
    // validate
    var $selClasses = $("#div-class .selected");
    if ($selClasses.length < 2) {
        error("请在左侧第二步选择要至少两个班级！");
        return;
    }
    var datas = "[";
    for (var i = 0; i < $selClasses.length; i++) {
        var $class = $($selClasses[i]);
        var classId = $class.attr("classId");
        var teacherId = $class.attr("teacherId");
        var groupId = $class.attr("groupId");
        if(!checkPreSchedule(classId, teacherId)){
            error("所选合班课已设置预排，请先在预排中删除涉及合班的班级，再进行合班");
            return;
        }
        // 有一门课多个老师上的情况，要拆分老师
        //var teacherIdArr = teacherIds.split(",");
        //for (var ii = 0; ii < teacherIdArr.length; ii++) {
        //    var teacherId = teacherIdArr[ii];
        //
        //    var data = '{"taskId":' + taskId + ', "courseId":' + courseId
        //        + ', "classId":' + classId + ',"teacherId":' + teacherId + '}';
        //
        //    if (ii != teacherIdArr.length - 1) {
        //        data += ",";
        //    }
        //
        //    datas += data;
        //}
        var data = '{"taskId":' + taskId + ', "courseId":' + courseId +', "classId":'+classId +',"teacherId":'+teacherId +', "groupId" :' +groupId +'}';
        datas += data;
        if (i != $selClasses.length - 1) {
            datas += ",";
        }
    }
    datas = datas + "]";
    $.ajax({
        type: "POST",
        cache: false,
        url: "/m/rule/addMergedClass?taskId=" + taskId,
        contentType: "application/json", //必须有
        dataType: "json", //表示返回值类型，不必须
        data: datas,
        success: function (result) {
            if (result.code == 1) {
                success("添加合班成功！");
                getUnMergedClasses();
                getMergedClasses();
            } else {
                error(result.msg);
            }
        }
    });
}
function removeMergedClass() {
    var $selClasses = $("#div-mergedclass .selected");
    if ($selClasses.length <= 0) {
        error("请在右侧选择一个您要拆分的合班！");
        return;
    }
    var groupNo = $($selClasses[0]).attr("groupNo");
    jQuery.ajax({
        url: "/m/rule/removeMergedClass?taskId=" + taskId + "&groupNo=" + groupNo,
        cache: false,
        success: function (ret) {
            var result = eval(ret);
            if (result.code == 1) {
                success("删除合班成功！");
                $("#div-mergedclass a[groupNo='" + groupNo + "']").remove();
                getUnMergedClasses(); // reload classes
            } else if (result.code = -1) {
                error("不允许删除！");
            } else {
                error("删除失败！");
            }
        }
    });
}

/**
 * 获取已合并的班级
 */
function getMergedClasses() {
    if (courseId <= 0) {  // no selected course
        return;
    }
    jQuery.ajax({
        url: "/m/rule/getMergedClasses?taskId=" + taskId,
        cache: false,
        success: function (ret) {
            if (ret != "") {
                var mergedClasses = eval(ret);
                var $div = $("#div-mergedclass");
                $div.empty();
                for (var i = 0; i < mergedClasses.length; i++) {
                    // <a href="javascript:void(0)" class="list-group-item" key="" groupNo=""></a>
                    var cls = mergedClasses[i];
                    var $a = $(document.createElement("a"));
                    $a.attr("href", "javascript:void(0)");
                    $a.text(cls.names);
                    $a.addClass("list-group-item");
                    $a.attr("key", cls.key);
                    $a.attr("groupNo", cls.id);
                    $a.click(function () {
                        $("#div-mergedclass a").removeClass("selected");
                        $(this).addClass("selected");
                    });
                    $div.append($a[0]);
                }
            }
        }
    });
}

function success(msg) {
    var $tips = $("#tips");
    $tips.removeClass("alert-success").removeClass("alert-info").removeClass("alert-warning").removeClass("alert-danger");
    $tips.addClass("alert-success").text(msg).show().fadeOut(10000);
}
function error(msg) {
    var $tips = $("#tips");
    $tips.removeClass("alert-success").removeClass("alert-info").removeClass("alert-warning").removeClass("alert-danger");
    $tips.addClass("alert-warning").text(msg).show().fadeOut(10000);
}

/*从此步重新开始*/
function reStartFromHere(where) {
    var ret = reStartFromWhere(where);
    if (ret == true) {
        //to do
        $("#reStartNotice").text('设置成功').fadeOut(5000);
    } else {
        //to do
        $("#reStartNotice").text('设置失败').fadeOut(5000);
    }
    location.reload();
}

$(document).ready(function(){
    //为了判断是否能合班
    teachingPlanList = null;
    $.ajax({
        url: "/m/teachingplan/listForMultiTeachers?taskId=" + taskId,
        cache: false,
        success: function (ret) {
            if (ret != "") {
                teachingPlanList = eval(ret);
            }
            $("#btn-add").removeAttr("disabled");
        }
    });
});